package com.lungle.warmdiary.app.view.active.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.HttpHelper;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.ActiveCommentUpdatePost;
import com.lungle.warmdiary.app.model.response.Active;
import com.lungle.warmdiary.app.model.response.Image;
import com.lungle.warmdiary.app.utils.DateUtil;
import com.lungle.warmdiary.app.utils.LoadLocalImageUtil;
import com.lungle.warmdiary.app.utils.StringUtils;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class CommentScreenShotFragment extends BaseFragment {
    private static final String COMMENT_SCREEN_SHOT_SCREEN = "comment screen shot screen";
    private final int CODE_SELECT = 1;

    @Bind(R.id.et_like)
    EditText mEtLike;
    @Bind(R.id.iv_like_clear)
    ImageView mIvLikeClear;
    @Bind(R.id.et_comment)
    EditText mEtComment;
    @Bind(R.id.iv_comment_clear)
    ImageView mIvCommentClear;

    @Bind(R.id.iv_select)
    ImageView mIvSelect;

    private Active mActive;
    private String mDisplayImage;

    private boolean isUpload = false;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_commet_screenshot, container, false);
        initData();
        initView(view);
        return view;
    }


    @Override
    public void initData() {
        mActive = (Active) getArguments().getSerializable("active");
        if (DateUtil.isThreeDayLater(DateUtil.getDate(mActive.getEndtime()), HttpHelper.getServerTime())) {
            isUpload = false;
        } else {
            isUpload = true;
        }


    }

    @Override
    public void initView(View view) {
        ButterKnife.bind(this, view);

        if (!isUpload) {
            mEtLike.setEnabled(false);
            mEtComment.setEnabled(false);

        } else {
            mEtLike.addTextChangedListener(UIHelper.getTextWatcher(getActivity(), mIvLikeClear));
            mEtComment.addTextChangedListener(UIHelper.getTextWatcher(getActivity(), mIvCommentClear));
        }

        if (mActive.getNcomment() != 0)
            mEtComment.setText(mActive.getNcomment() + "");
        if (mActive.getNlike() != 0)
            mEtLike.setText(mActive.getNlike() + "");
        if (mActive.getResultScreenshot1() != null) {
            mDisplayImage = mActive.getResultScreenshot1();
            ImageLoader.getInstance().displayImage(StringUtils.getPreviewImageUrl(mActive.getResultScreenshot1()), mIvSelect);

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(COMMENT_SCREEN_SHOT_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(COMMENT_SCREEN_SHOT_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == CODE_SELECT) {
            ArrayList<String> images = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            if (!images.isEmpty()) {
                mDisplayImage = images.get(0);
                LoadLocalImageUtil.getInstance().displayFromSDCard(mDisplayImage, mIvSelect);
            }

        }
    }

    @Override
    public boolean onBackPressed() {
        TDevice.hideSoftKeyboard(getActivity().getWindow().getDecorView());
        return super.onBackPressed();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (isUpload) {
            getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);
            menu.findItem(R.id.login_menu_send);
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (isUpload) {
            if (prepareSubmit()) {
                uploadFile(new File(mDisplayImage));
            }
        } else {
            AppContext.showToastShort("当前活动不可操作");
        }


        return true;
    }

    private void uploadFile(File file) {
        showWaitDialog("正在上传...");
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        ApiFactory.getFileApi().upload(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Image>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        if (canUpdateActiveState()) {
                            updateActiveState();
                        } else {
                            setResultData();
                            hideWaitDialog();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<Image> result) {
                        mActive.setResultScreenshot1(result.getData().getUrl());
                        mActive.setNcomment(Integer.valueOf(mEtComment.getText().toString().trim()));
                        mActive.setNlike(Integer.valueOf(mEtLike.getText().toString().trim()));
                    }
                });
    }


    private void setResultData() {
        Intent intent = new Intent();
        intent.putExtra(ActiveDetailFragment.ARGS_RESPONSE, mActive);
        getActivity().setResult(ActiveDetailFragment.CODE_RESPONSE_COMMENT, intent);
        getActivity().finish();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.iv_like_clear, R.id.iv_comment_clear, R.id.iv_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_like_clear:
                mEtLike.getText().clear();
                mEtLike.requestFocus();
                break;
            case R.id.iv_comment_clear:
                mEtComment.getText().clear();
                mEtComment.requestFocus();
                break;
            case R.id.iv_select:
                if (isUpload) {
                    TDevice.hideSoftKeyboard(view);
                    PhotoPicker.builder()
                            .setPhotoCount(1)
                            .setShowCamera(false)
                            .setPreviewEnabled(false)
                            .start(getActivity(), this, CODE_SELECT);
//                    PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
//                    intent.setPhotoCount(1);
//                    intent.setShowCamera(false);
//                    startActivityForResult(intent, CODE_SELECT);
                    return;
                }

                if (!TextUtils.isEmpty(mActive.getResultScreenshot1())) {

//                    ImagePreview2 imagePreview2= new ImagePreview2(getContext());
//                    imagePreview2.showPreview(view, mActive.getResultScreenshot1());
                    ArrayList<String> arrayList = new ArrayList<>(1);
                    arrayList.add(mActive.getResultScreenshot1());
                    PhotoPreview.builder()
                            .setPhotos(arrayList)
                            .setCurrentItem(0)
                            .setShowDeleteButton(true)
                            .start(getActivity(), this);
                }
//                mImagePreview.showPreview(view, mActive.getResultScreenshot1());


                break;
        }
    }


    private boolean prepareSubmit() {
        if (TextUtils.isEmpty(mEtLike.getText().toString())) {
            AppContext.showToastShort("请填写点赞数");
            return false;
        }

        if (TextUtils.isEmpty(mEtComment.getText().toString())) {
            AppContext.showToast("请填写评论数");
            return false;
        }

        if (TextUtils.isEmpty(mDisplayImage)) {
            AppContext.showToast("请上传截图");
            return false;
        }

        return true;

    }


    private boolean canUpdateActiveState() {
        if (mActive.getNlike() > 0 && mActive.getNcomment() > 0 & (mActive.getResultScreenshot2() != null && !mActive.getResultScreenshot2().isEmpty()) && !TextUtils.isEmpty(mActive.getResultScreenshot1())) {
            return true;
        }
        return false;
    }

    private void updateActiveState() {
        showWaitDialog("正在更新...");
        ActiveCommentUpdatePost.CampaignProcess campaignProcess = new ActiveCommentUpdatePost.CampaignProcess(mActive.getNcomment(),
                mActive.getNlike(), mActive.getResultScreenshot2(), mActive.getResultScreenshot1());
        ActiveCommentUpdatePost campaignProcessPost = new ActiveCommentUpdatePost(campaignProcess);
        ApiFactory.getUserApi().updateActiveState(mActive.getId(), mActive.getMediaid(), campaignProcessPost).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        setResultData();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result result) {
                        AppContext.showToast("更新成功");
                    }
                });
    }

}
